﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Data.Model;
using ZLCMS.Business.Util;
using NHibernate;
using DotNet.Common.NHibernateUtil;
using System.IO;

namespace ZLCMS.Web.SystemManage.Basics.FormInfo
{
    public partial class FormObjectList : System.Web.UI.Page
    {
        protected ZLCMS.Business.DwzFrame.FrameHelper _framePage;

        protected IList<SysFormField> Fields { get; set; }

        protected int FormId { get; set; }

        protected int UnHandlerCount { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            _framePage = new ZLCMS.Business.DwzFrame.FrameHelper(this);

            FormId = Int32.Parse(Request["formid"]);
            //设置分页大小
            int pageSize = _framePage.IsAjaxPagerPostBack ? _framePage.PageSize : 20;

            //设置页码
            int pageIndex = _framePage.IsAjaxPagerPostBack ? _framePage.PageIndex : 1;
            //判断是否导出EXCEL操作
            if (!string.IsNullOrEmpty(Request["exportexcel"]))
            {
                ExportExcel();
            }
            else
            {
                using (NHibernate.ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    //设置记录总数
                    _framePage.RecordCount = Convert.ToInt32(session.CreateQuery("select count(*) from SysFormObjectDef where OwnerAccount=:acc and FormId=:fid ")
                        .SetParameter("acc", UserKit.GetUserAccountFailLogin())
                        .SetParameter("fid", FormId)
                        .UniqueResult());
                    UnHandlerCount = Convert.ToInt32(session.CreateQuery("select count(*) from SysFormObjectDef where OwnerAccount=:acc and FormId=:fid and ObjectStatus='0'")
                        .SetParameter("acc", UserKit.GetUserAccountFailLogin())
                        .SetParameter("fid", FormId)
                        .UniqueResult());

                    //设置数据源
                    repeaterObjects.DataSource = session.CreateQuery("from SysFormObjectDef where OwnerAccount=:acc and FormId=:fid order by ObjectStatus,Id desc")
                        .SetParameter("acc", UserKit.GetUserAccountFailLogin())
                        .SetParameter("fid", FormId)
                        .SetFirstResult((pageIndex - 1) * pageSize)
                        .SetMaxResults(pageSize)
                        .List<SysFormObjectDef>();

                    Fields = session.CreateQuery("from SysFormField where FormId=" + FormId + " order by Sort").List<SysFormField>();

                    repeaterFields.DataSource = Fields;
                }
                repeaterFields.DataBind();
                repeaterObjects.DataBind();
            }
        }
        
        
        protected void ExportExcel()
        {
            using (NHibernate.ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                Fields = session.CreateQuery("from SysFormField where FormId=" + FormId + " order by Sort").List<SysFormField>();

                StringWriter sw = new StringWriter();
                //sw.WriteLine("列1\t列2\t列3\t列4");
                int loopCounter = 0;
                string header_data = ""; 
                foreach(SysFormField item in Fields)
                {
                    header_data += item.FieldName + "\t";
                    loopCounter++;

                }
                header_data += "记录时间";
                sw.WriteLine(header_data);

                IList<SysFormObjectDef> list = session.CreateQuery("from SysFormObjectDef where OwnerAccount=:acc and FormId=:fid order by ObjectStatus,Id desc")
                        .SetParameter("acc", UserKit.GetUserAccountFailLogin())
                        .SetParameter("fid", FormId)
                        .List<SysFormObjectDef>();


                foreach (SysFormObjectDef item in list)
                {
                    string data = "";

                    loopCounter = 0;
                    foreach (SysFormField field in Fields)
                    {
                        string val = session.CreateSQLQuery("select value from sys_form_object_field where object_id=:oid and field_id=:fid")
                            .SetParameter("oid", item.Id)
                            .SetParameter("fid", field.Id)
                            .UniqueResult<string>();
                        if (string.IsNullOrEmpty(val))
                        {
                            val = "未填";
                        }
                        data += val + "\t";
                    }
		    data += string.Format("{0:yyyy-MM-dd hh:mm:ss}", item.RecordDate);
                    sw.WriteLine(data);
                }
                sw.Close();

                OutputKit.OutputExcel(Response, sw);
            }
        }

        protected void repeaterObjects_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                IList<string> values = new List<string>();
                SysFormObjectDef formObject = e.Item.DataItem as SysFormObjectDef;
                using (ISession session = SessionFactoryHelper.CreateSession())
                {
                    foreach (SysFormField item in Fields)
                    {
                        values.Add(session.CreateSQLQuery("select value from sys_form_object_field where object_id=:oid and field_id=:fid")

                            .SetParameter("oid", formObject.Id)
                            .SetParameter("fid", item.Id)
                            .UniqueResult<string>());
                    }
                }
                Repeater rep = e.Item.FindControl("repeaterFields") as Repeater;//找到里层的repeater对象

                rep.DataSource = values;
                rep.DataBind();
            }
        }
    }
}